<template>
  <diV class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell v-for="(article,index) in list" :key="index" :title="article.title" />
    </van-list>
  </diV>
</template>



<script>
import {getSearchResultAPI} from '@/api';

export default {
  name:'SearchResult',
  props:{
    searchText:{
      type:String,
      required:true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page:1,  //页码值
      perpage:20,  //每页的大小
      error: false,
    };
  },
  methods: {
     onLoad() {
        
          // 模拟出错
          // if(Math.random()>0.5){
          //   JSON.parse('jiogueiro')
          // }
          this.time=setTimeout(async() => {
            try{
              // 1.请求获取数据
              const {data}=await getSearchResultAPI({
                page:this.page,
                per_page:this.perpage,
                q:this.searchText
              })
            
              // 2.将数据添加到数组列表中
              const {results}=data.data
              this.list.push(...results)
              // 3.关闭loading
              this.loading=false
              // 4.判断是否还有数据
              if(results.length){
                this.page++
              }else{
                this.finished=true
              }

            } catch(err){
              this.error=true
              this.loading=false
              this.$toast('获取数据失败,请稍后重试!!')
            }  
          }, 500);
          
        
        
    },
  },
  beforeDestroy(){
    this.time=null
  }
}
</script>

<style>

</style>